package com.nogroup.springbootproject.controller;

import com.nogroup.springbootproject.dto.BookDto;
import com.nogroup.springbootproject.dto.CourseDto;
import com.nogroup.springbootproject.entity.Book;
import com.nogroup.springbootproject.entity.Course;
import com.nogroup.springbootproject.service.BookService;
import com.nogroup.springbootproject.utils.PageUtils;
import com.nogroup.springbootproject.utils.result.DataResult;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.util.List;

/**
 * (Book)表控制层
 *
 * @author makejava
 * @since 2024-04-07 18:45:28
 */
@RestController
@RequestMapping("book")
public class BookController {
    /**
     * 服务对象
     */
    @Resource
    private BookService bookService;

    /**
     * 分页查询
     *
     * @param book 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<Book>> queryByPage(Book book, PageRequest pageRequest) {
        return ResponseEntity.ok(this.bookService.queryByPage(book, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<Book> queryById(@PathVariable("id") String id) {
        return ResponseEntity.ok(this.bookService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param book 实体
     * @return 新增结果
     */
    @RequestMapping("insertBook")
    @PostMapping
    public DataResult add(Book book) {
        return DataResult.successByData(this.bookService.insert(book));
    }

    /**
     * 编辑数据
     *
     * @param book 实体
     * @return 编辑结果
     */
    @RequestMapping("edit")
    @PutMapping
    public DataResult edit(Book book) {
        return DataResult.successByData(this.bookService.update(book));
    }

    /**
     * 删除数据
     *
     * @param book 主键
     * @return 删除是否成功
     */
    @RequestMapping("deleteById")
    @DeleteMapping
    public DataResult deleteById(Book book) {
        return DataResult.successByData(this.bookService.deleteById(book));
    }

    @RequestMapping("getAllBooks")
    public DataResult getAllBooks(){
        List<Book> books = bookService.getAllBooks();
        return DataResult.successByDatas(books);
    }

    @RequestMapping("getBooksByFuzzySearch")
    public DataResult getBooksByFuzzySearch(BookDto bookDto){
        long count = bookService.countPage(bookDto);
        int index = PageUtils.getStartPage(bookDto.getPage(), bookDto.getLimit());
        bookDto.setPage(index < count ? index : 0);
        List<Book> books = bookService.getBooksByFuzzySearch(bookDto);
        return DataResult.successByTotalData(books,count);
    }
}

